var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
const { expressjwt: expressJWT } = require("express-jwt");

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
var wmhRouter = require('./routes/wmh');
var ybkRouter = require('./routes/ybk');
var ycfRouter = require('./routes/ycf');
var yjrRouter = require('./routes/yjr');
var yzhRouter = require('./routes/yzh');
var zyhRouter = require('./routes/zyh');



var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/yjr/upload', express.static(path.join(__dirname, 'upload')));

// 前端接口加上这个前缀访问自己的接口   尽量别动

app.use('/wmh', wmhRouter);
app.use('/ybk', ybkRouter);
app.use('/ycf', ycfRouter);
app.use('/yjr', yjrRouter);
app.use('/zyh', zyhRouter);
app.use('/yzh', yzhRouter);

app.use(
  expressJWT({ secret: "abcdefg", algorithms: ["HS256"] }).unless({
    path: ["/ybk/login", '/ybk/refresh', '/ybk/getCode',], // 跳过token验证
  })
);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  const authorization = req.headers["authorization"];
  if (!authorization) {
    return res.status(401).json({
      code: 2000,
      message: "请先登录"
    })
  }
  if (err.name === 'UnauthorizedError') {
    return res.status(401).json({
      code: 2000,
      message: "登录过期"
    })
  }
});

module.exports = app;
